﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

namespace Facebook
{
    /// <summary>
    /// Utilities class for handing facebook security items
    /// </summary>
    internal static class Security
    {
        /// <summary>
        /// Generate a MD5 hash of the parameters as required by Facebook
        /// http://wiki.developers.facebook.com/index.php/How_Facebook_Authenticates_Your_Application
        /// </summary>
        /// <param name="parameters">A Sorted dictionary of parameters are required - the sort order is inportant to the resulting hash</param>
        /// <returns></returns>
        internal static string GenerateFacebookParametersMD5Hash(SortedDictionary<string, string> parameters, string facebookSecret)
        {
            var parametersForSignature = new StringBuilder(); // for building a string of the input parameters

            foreach (string key in parameters.Keys) // Append sorted parameters to a string in Invariant culture
                parametersForSignature.Append(String.Format(CultureInfo.InvariantCulture, "{0}={1}", key, parameters[key]));
            parametersForSignature.Append(facebookSecret); // Add the facebook secret to the hash as required by, you guessed it, facebook

            // compute the hash
            var md5Crypto = new MD5CryptoServiceProvider();
            byte[] data = Encoding.ASCII.GetBytes(parametersForSignature.ToString());
            data = md5Crypto.ComputeHash(Encoding.UTF8.GetBytes(parametersForSignature.ToString()));

            // convert the result to hex and return
            var md5HashToReturn = new StringBuilder();
            for (int i = 0; i < data.Length; i++) md5HashToReturn.Append(data[i].ToString("x2"));
            return md5HashToReturn.ToString().ToLower();
        }
    }
}
